package nancal.mp.mvc


import nbcp.base.comm.ApiResult
import nbcp.base.extend.HasValue
import nbcp.base.utils.FileUtil
import nbcp.base.utils.ShellUtil
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

@RestController
class ShellController {
    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }

    @PostMapping("/shell/mkdir")
    fun mkdir(@RequestParam("path") path: String, @RequestParam("subs", required = false) subs: String?) {
        //检测非法注入
        var invalidChars = " ;&|\n".toList()
        if (path.toCharArray().intersect(invalidChars).size > 0) {
            throw RuntimeException("路径包含非法字符");
        }


        if (subs.HasValue) {
            if (subs!!.toCharArray().intersect(invalidChars).size > 0) {
                throw RuntimeException("子路径包含非法字符");
            }

            subs.split(",")
                .filter { it.isNotEmpty() }.forEach {
                    var p = FileUtil.resolvePath(path, it);
                    ShellUtil.execRuntimeCommand("mkdir -p " + p)
                }
        } else {
            ShellUtil.execRuntimeCommand("mkdir -p " + path)
        }
    }

    @PostMapping("/shell/run-11")
    fun run11(@RequestParam("app") app: String): ApiResult<String> {
        return ShellUtil.execRuntimeCommand("/app/java/run-11.sh " + app, path = "/app/java")
    }

    @PostMapping("/shell/run-17")
    fun run17(@RequestParam("app") app: String): ApiResult<String> {
        return ShellUtil.execRuntimeCommand("/app/java/run-17.sh " + app, path = "/app/java")
    }

    @PostMapping("/shell/run-ng")
    fun runng(): ApiResult<String> {
        return ShellUtil.execRuntimeCommand("/app/web/run-ng.sh", "/app/web");
    }
}

